// pages/house/RentalHouseDetail/oldHouseShare/oldHouseShare.js
import api from "../../../../common/api";
import util from "../../../../utils/util";
import { getActiveStr } from "../../../../utils/utilsNew";
import p from "../../../../utils/platform";
import CanvasManager from "../../../../common/CanvasManager";
const { houseLayout } = require("../../../../utils/config");

const app = getApp();

// 相对单位
let rpx = 1;
// 图片保存到本地的路径
let saveImgPromise = null;
let logoScale = 0.5;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    banner1: "https://api.shulanfd.com/aist-filesvr-web/api/files/e7e0f6b3def6422186c32c4cb1e29b25",
    labelImgList: {
      NEWHOUSE: "images/1.png",
      SALES: "images/2.png",
      RENT: "images/3.png",
    },
    IMG_MAX_LENGTH: 7,
    content: {},
    jingjiId: {},
    copyShowDialog: false,
    canvasWidth: 750,
    canvasHeight: 1334,
    avatar: "",
    posterLogo: "",
    logoHeight: 80 * logoScale,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onReady: function () {
    const info = app.globalData.houseShareBannerInfo;
    var content = info.roomDetail || p.getStorageSync("_wx_roomDetail");
    var jingjiId = info.allId || p.getStorageSync("_wx_allId");
    p.setStorageSync("_wx_roomDetail", content);
    p.setStorageSync("_wx_allId", jingjiId);

    // 新房数据
    if (content.isNewHouse) {
      content.buildSize = content.build_size;
      content.resblockName = content.resblock_name;
      content.delegationType = "NEWHOUSE";
      content.max_size = content.max_size || 0;
      content.min_size = content.min_size || 0;
    }

    app.globalData.loginPromise.then(() => {
      const deviceInfo = app.globalData.deviceInfo;
      rpx = deviceInfo.windowWidth / 750;

      let canvasWidth = 750 * rpx;
      let canvasHeight = deviceInfo.windowHeight;
      let avatar = jingjiId.wxHeadImg || "/images/default_head.png";

      // 删除太长的头像
      delete jingjiId.wxHeadImg;

      const fn = async () => {
        content.houImageVO.length = Math.min(content.houImageVO.length, this.data.IMG_MAX_LENGTH);
        if (content.houImageVO.length == 0) {
          content.houImageVO = [app.globalData.defaultHouseUrl];
        }

        const posterLogo = await this.getLogo();
        const logoHeight = posterLogo ? this.data.logoHeight : 0;
        const height = (houseLayout[content.houImageVO.length].height + 320 + logoHeight) * rpx;
        canvasHeight = Math.max(height, canvasHeight);

        this.setData({
          canvasWidth,
          canvasHeight,
          content,
          jingjiId,
          avatar,
          posterLogo,
        });

        const page = this.data.content.isNewHouse ? "newRentalHouseDetail" : "RentalHouseDetailLite";
        const QrCode = await this.fetchLongToShort(this.data.jingjiId, page);

        let imgList = [this.data.banner1, this.data.avatar, QrCode];
        if (this.data.posterLogo) {
          imgList.push(this.data.posterLogo);
        }
        imgList.push(...this.data.content.houImageVO);
        saveImgPromise = Promise.all(
          imgList.map((url) => {
            return this.saveImgToPhotosAlbumTap(url);
          })
        );

        await this.drawCanvas()

        console.log("海报绘制ok");
      };

      if (content.isNewHouse) {
        this.getNewHouseTypesImgs(content.hd_new_house_resblock_id).then((list) => {
          content.houImageVO = list;
          fn();
        });
      } else {
        content.houImageVO = this.houImageVOFn(content.houImageVO);
        fn();
      }
    });
  },

  getLogo() {
    return new Promise((resolve, reject) => {
      api.getBindShop({}, (res) => {
        const content = res.data.content || {};
        if (content.shopId && content.bindStatus == "2") {
          api.getShopInfo({ shopId: content.shopId }, (res) => {
            const { isSuccess, content } = res.data;
            if (isSuccess) {
              let logo = content.posterLogo || "";
              if (logo && logo.indexOf("http") == -1) {
                logo = "https://api.shulanfd.com/aist-filesvr-web/api/files/27da0cecb14c493ba511bb09e6c56a84";
              }
              resolve(logo);
            } else {
              resolve("");
            }
          });
        } else {
          resolve("");
        }
      });
    });
  },

  // 新房的户型图获取
  getNewHouseTypesImgs(id) {
    return new Promise((resolve, reject) => {
      api.getNewhousetype({ houseResblockId: id }, (res) => {
        const list = res.data.content;
        const fetchList = [];
        let total = 0;

        for (let i = 0; i < list.length; i++) {
          total = total + list[i].num;
          fetchList.push(list[i].room_type);
          if (total >= this.data.IMG_MAX_LENGTH) break;
        }

        Promise.all(fetchList.map((v) => this.getNewhouseImg(id, v))).then((res) => {
          const result = [];
          res.forEach((item) => {
            result.push(...item);
          });

          resolve(result);
        });
      });
    });
  },

  getNewhouseImg(id, type) {
    return new Promise((resolve, reject) => {
      api.getNewhouseImg(
        {
          houseResblockId: id,
          roomType: type,
        },
        (res) => {
          try {
            const imgList = res.data.content.map((v) => v.fileId);
            resolve(imgList);
          } catch (error) {
            
          }
        }
      );
    });
  },

  // 链接地址的长转短
  fetchLongToShort(jingjiId, page) {
    return new Promise((resolve, reject) => {
      //长链接--短
      api.qrcodeLongToShort(JSON.stringify(jingjiId), {}, (res) => {
        let smallCode = res.data.content;
        const QrCode =
          util.domain +
          "miniCode/getWXACodeUnlimit?page=" +
          encodeURI(`pages/houseShare/${page}/${page}`) +
          "&scene=" +
          smallCode +
          "&miniName=zhaofangjs";

        resolve(QrCode);
      });
    });
  },

  drawCanvas() {
    const houseInfo = this.data.content;
    const jingjiId = this.data.jingjiId;
    let buildSize = houseInfo.buildSize > 0 ? houseInfo.buildSize + "㎡" : "---";
    let totalPrices = houseInfo.totalPrices > 0 ? houseInfo.totalPrices : "---";
    if (houseInfo.totalPrices > 0) {
      if (houseInfo.delegationType == "RENT") {
        totalPrices = totalPrices + "元";
      } else {
        totalPrices = totalPrices / 10000 + "万";
      }
    }

    if (houseInfo.isNewHouse) {
      buildSize =
        [houseInfo.min_size, houseInfo.max_size]
          .filter((v) => !!v)
          .map((v, i, array) => {
            return array.length == 2 && i == 0 ? v : v + "㎡";
          })
          .join("~") || "---";

      if (houseInfo.average_price) {
        totalPrices =
          [houseInfo.min_size, houseInfo.max_size]
            .filter((v) => !!v)
            .map((v, i, array) => {
              let p = Math.floor((v * houseInfo.average_price) / 10000);
              return array.length == 2 && i == 0 ? p : p + "万";
            })
            .join("~") || "---";
      }
    }
    const fontSize = houseInfo.isNewHouse ? 34 : 42;
    const resblockName = getActiveStr(houseInfo.resblockName || "---", 16);
    const realName = jingjiId.realName ? getActiveStr(jingjiId.realName, 14) + "为您推荐" : "---";
    const mobile = jingjiId.mobile ? "联系方式：" + jingjiId.mobile : "---";

    const room = houseInfo.room > 0 ? houseInfo.room + "室" : "";
    const hall = houseInfo.hall > 0 ? houseInfo.hall + "厅" : "";
    const roomHall = room + hall ? room + hall : "---";
    const average_price = houseInfo.average_price ? houseInfo.average_price / 10000 + "万/㎡" : "---";
    const thirdName = houseInfo.isNewHouse ? "均价" : "居室";

    wx.showLoading({
      title: "加载中",
    });

    return new Promise((resolve, reject) => {
      saveImgPromise.then((result) => {
        let banner1 = result[0].path;
        let avatar = result[1].path;
        let QrCode = result[2].path;
        let posterLogo = this.data.posterLogo ? result[3].path : null;
        let sliceIndex = posterLogo ? 4 : 3;
        const houImagesList = result.slice(sliceIndex);
        const layout = houseLayout[houImagesList.length];
        const logoHeight = posterLogo ? this.data.logoHeight : 0;

        let context = wx.createCanvasContext("share"); //这里的“share”是“canvas-id”
        const cm = new CanvasManager(rpx, context);

        context.clearRect(0, 0, 750 * rpx, this.data.canvasHeight);
        cm.drawRect(0, 0, 750, this.data.canvasHeight / rpx, "#fff");

        // 顶部背景
        cm.drawImage(banner1, 0, 0, 750, 526);
        cm.drawCircle("#fff", 100, 130, 55);
        cm.drawCirImage(100, 100, 50, 80, avatar);

        cm.drawText(42, "#fff", realName, 180, 80, true);
        cm.drawText(28, "#fff", mobile, 180, 134);

        // 白色的圆角矩形背景
        const _h1 = (this.data.canvasHeight - (220 + 50 + logoHeight) * rpx) / rpx;
        cm.roundedRect(30, 220, 690, _h1, 5, "#fff", true);

        cm.drawText(24, "#808080", "总价", 70, 390);
        cm.drawText(24, "#808080", "面积", 287, 390);
        cm.drawText(24, "#808080", thirdName, 496, 390);

        cm.drawText(fontSize, "#F75353", totalPrices, 70, 430, true);
        cm.drawText(fontSize, "#000", buildSize, 287, 430, true);
        cm.drawText(fontSize, "#000", houseInfo.isNewHouse ? average_price : roomHall, 496, 430, true);

        cm.drawText(52, "#000", resblockName, 66, 270, true);
        cm.drawText(24, "#000", "长按识别查看更多房源信息", 230, layout.height + 200);

        cm.drawImage(this.data.labelImgList[houseInfo.delegationType], 560, 270, 170, 60);
        layout.list.forEach((item, index, array) => {
          let { width, height, path } = houImagesList[index];
          const { x, y, w, h } = item;
          cm.roundedRectImage(x, y - 50, w, h, width, height, 5, path, array);
        });

        cm.drawCirImage(187, 187, 280, layout.height, QrCode);

        if (posterLogo) {
          cm.drawImage(
            posterLogo,
            (750 - 360 * logoScale) / 2,
            (this.data.canvasHeight - (logoHeight + 20) * rpx) / rpx,
            360 * logoScale,
            logoHeight
          );
        }

        context.draw(true, () => {
          wx.hideLoading();
          let delay = app.globalData.deviceInfo.isIOS ? 0 : 500;
          setTimeout(() => {
            this.canvasToTempFilePath().then((tempFilePath) => {
              p.showToast({
                title: "完成！",
                icon: "success",
              });
              resolve(tempFilePath)
            })
          }, delay);
        });
      });
    });
  },

  canvasToTempFilePath() {
    return new Promise((resolve, reject) => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 750 * rpx,
        height: this.data.canvasHeight,
        destWidth: 750 * rpx * 4,
        destHeight: this.data.canvasHeight * 4,
        canvasId: "share",
        success: (a) => {
          resolve(a.tempFilePath);
        },
        fail: (err) => {
          console.log("绘制error", err);
        },
      });
    })
  },

  // 房源图片的处理
  houImageVOFn(list) {
    list = list || [];
    list.sort((item) => {
      return item.tagName == "户型图" ? -1 : 1;
    });
    list = list.map((v) => v.url);
    return list;
  },

  hanldeSaveImage() {
    this.drawCanvas().then((tempFilePath) => {
      wx.saveImageToPhotosAlbum({
        filePath: tempFilePath,
        success: () => {
          // console.log("保存海报成功", (new Date()).getSeconds());
        },
        fail: () => {
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting["scope.writePhotosAlbum"]) {
                wx.showModal({
                  title: "提示",
                  content: "需要获取图片权限哦",
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting();
                    }
                  },
                });
              }
            },
          });
        },
      });
    });
  },

  hanldePreviewImage() {
    this.drawCanvas().then((tempFilePath) => {
      wx.previewImage({
        urls: [tempFilePath],
      });
    });
  },

  saveImgToPhotosAlbumTap(value) {
    return new Promise((resolve, reject) => {
      if (!value) return resolve("");
      wx.getImageInfo({
        src: value,
        success: function (res) {
          resolve(res);
        },
        fail: () => {
          this.saveImgToPhotosAlbumTap(app.globalData.defaultHouseUrl).then(resolve);
        },
      });
    });
  },
});
